from google.appengine.ext import webapp
from google.appengine.ext.webapp.util import run_wsgi_app
from google.appengine.api import urlfetch
import re
import urllib

class MainPage(webapp.RequestHandler):
    def get(self):
        # self.request.get method will auto urllib.unquote
        queryString = self.request.query_string.split('&')
        type = None
        environ = None
        rawquery = 'false'
        url = None
        method = 'POST'
        for i in queryString:
            if i.startswith('type='):
                type = i.replace('type=','',1)
            elif i.startswith('query='):
                environ = i.replace('query=','',1)
            elif i.startswith('rawquery='):
                rawquery = i.replace('rawquery=','',1).lower()
            elif i.startswith('url='):
                url = i.replace('url=','',1)
            elif i.startswith('method='):
                method = i.replace('method=','',1).upper()
        if url == None:
            raise Error, "argument url is not defined!"
        url = urllib.unquote(url)
        remoteLocation = re.match(r'^(((?:(?:((?:[a-zA-Z]+)?)\:\/\/(?:(?:[^\/\:\@\?\#]+)(?:\:(?:[^\/\:\@\?\#]+))?\@)?[^\/\:\@\?\#]+(?:\.[^\/\:\@\?\#])*\.?(?:\:\d+)?)?)?)(?:\/(?:[^\/\?\#]+(?:\/[^\/\?\#]+)*\/?)?)?)((?:\?[^\?\#]*)?)((?:\#[^\#]*)?)$', url)
        if remoteLocation == None:
            raise Error, "wrong format of argument url!"
        payload = None
        if environ != None:
            if rawquery == 'true':
                payload = urllib.unquote(environ)
            else:
                payload = environ.replace('|', '&')
        headers = {}
        if method == 'POST':
            headers['Content-Type'] = 'application/x-www-form-urlencoded'
        userAgent = self.request.headers['User-Agent']
        if userAgent != None:
            headers['User-Agent'] = userAgent
        result = urlfetch.fetch(url,
                                payload=payload,
                                method=method,
                                headers=headers,
                                follow_redirects=False,
                                deadline=10)
        self.response.set_status(result.status_code)
        for i in result.headers:
            if i.lower() != 'location':
                self.response.headers[i] = result.headers[i]
            else:
                header = result.headers[i]
                location = re.match(r'^((?:(?:((?:[a-zA-Z]+)?)\:\/\/(?:(?:[^\/\:\@\?\#]+)(?:\:(?:[^\/\:\@\?\#]+))?\@)?[^\/\:\@\?\#]+(?:\.[^\/\:\@\?\#])*\.?(?:\:\d+)?)?)?)(?:\/(?:[^\/\?\#]+(?:\/[^\/\?\#]+)*\/?)?)?((?:\?[^\?\#]*)?)((?:\#[^\#]*)?)$', header)
                if location == None:
                    self.response.headers[i] = result.headers[i]
                elif location.group(1) == '':
                    self.response.headers[i] = remoteLocation.group(2) + result.headers[i]
                elif location.group(2) == '':
                    self.response.headers[i] = remoteLocation.group(3) + result.headers[i]
                else:
                    self.response.headers[i] = result.headers[i]
        self.response.out.write(result.content)

application = webapp.WSGIApplication(
                                     [('/.*', MainPage)],
                                     debug=True)

def main():
    run_wsgi_app(application)

if __name__ == "__main__":
    main()